package Class016;

import Utils.ArrayUtils;

public class LinkedListWithArray {
    public static void main(String[] args) {
        ArrayLinkedList arrayLinkedList = new ArrayLinkedList(3);
        arrayLinkedList.addFirst(1);
        arrayLinkedList.addFirst(2);
        arrayLinkedList.addFirst(3);
        System.out.println(arrayLinkedList.pollFirst());
        System.out.println(arrayLinkedList.pollFirst());
        System.out.println(arrayLinkedList.pollFirst());
    }

    public static class ArrayLinkedList {
        public int[] linked_list;
        public int l;
        public int r;
        public int size;

        public ArrayLinkedList(int limit) {
            if(limit <= 0) {
                throw new RuntimeException("Non sense");
            }
            linked_list = new int[limit];
        }

        public void addFirst(int val) {
            if(isFull()) {
                System.out.println("Already Full");
                return;
            }
            linked_list[r] = val;
            r = nextIndex(r);
            size++;
        }

        public void addLast(int val) {
            if(isFull()) {
                System.out.println("Already Full");
                return;
            }
            linked_list[l] = val;
            l = preIndex(l);
            size++;
        }

        public int pollFirst() {
            if(isEmpty()) {
                System.out.println("Already Empty");
                return -114514;
            }
            int res = linked_list[r];
            r = preIndex(r);
            size--;
            return res;
        }

        public int pollLast() {
            if(isEmpty()) {
                System.out.println("Already Empty");
                return -114514;
            }
            int res = linked_list[l];
            l = nextIndex(l);
            size--;
            return res;
        }

        public int peekFirst() {
            if(isEmpty()) {
                System.out.println("Already Empty");
                return -114514;
            }
            return linked_list[r];
        }

        public int peekLast() {
            if(isEmpty()) {
                System.out.println("Already Empty");
                return -114514;
            }
            return linked_list[l];
        }

        public int nextIndex(int cur) {
            return (cur + 1) % linked_list.length;
        }

        public int preIndex(int cur) {
            return cur == 0 ? linked_list.length - 1 : cur - 1;
        }

        public boolean isEmpty() {
            return size == 0;
        }

        public boolean isFull() {
            return size == linked_list.length;
        }
    }
}
